<template>
    <el-form :model="formData" status-icon class="login-container" ref="formRef">
        <div id="login-panel">
            <div id="login_title">
                <h1>代码质量量化评估系统</h1>
            </div>
            <div class="input">
                <el-input v-model="formData.account" prefix-icon="User" placeholder="请输入用户名/邮箱"></el-input>
            </div>
            <div class="input">
                <el-input v-model="formData.password" prefix-icon="Lock" placeholder="请输入密码" show-password></el-input>
            </div>
            <div id="loginButtonGroup">
                <el-button @click="doLogin" style="width:100px" type="primary" :disabled="disabled">登录</el-button>
                <el-button @click="register_dialogFormVisible = true" style="width:100px" type="primary">注册</el-button>
            </div>
            <el-button @click="forgetPassword" style="float:right;margin-top:20px;" color="#626aef" 
                plain>忘记密码</el-button>
        </div>
    </el-form>
    <!-- 注册对话框 -->
    <el-dialog v-model="register_dialogFormVisible" title="注册">
        <div class="register-form">
            <el-form ref="registerRef" :model="data.form" status-icon :rules="data.form_rules" label-width="100px">
                <el-form-item label="用户名：" prop="account">
                    <el-input v-model="data.form.account" prefix-icon="User" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="邮箱：" prop="email">
                    <el-input v-model="data.form.email" prefix-icon="Message" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input type="password" v-model="data.form.password" prefix-icon="Lock" placeholder="请输入密码"
                        show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码：" prop="passwords">
                    <el-input type="password" v-model="data.form.passwords" prefix-icon="Lock" placeholder="请确认密码"
                        show-password></el-input>
                </el-form-item>

                <el-form-item prop="code" label="验证码：" style="margin-top: 20px;">
                    <el-row :gutter="10">
                        <el-col :span="14">
                            <el-input v-model="data.form.code"></el-input>
                        </el-col>
                        <el-col :span="10">
                            <el-button type="success" class="el-button-block" :loading="data.code_button_loading"
                                :disabled="data.code_button_disabled" @click="handlerGetCode">
                                {{ data.code_button_text }}
                            </el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="register_dialogFormVisible = false">关闭</el-button>
                <el-button type="primary" @click="submitForm" :disabled="data.submit_button_disabled"
                    :loading="data.submit_button_loading" class="el-button-block">
                    注册
                </el-button>
                <el-button type="danger" @click="resetForm">重置</el-button>
            </span>
        </template>
    </el-dialog>
</template>


<script>
import { computed, getCurrentInstance, reactive, ref, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { loginPost, GetCode, Register } from "../../api/http.js"
// 校验类
import { validate_email, validate_password, validate_code } from "../../utils/validate";
export default {
    name: "login",
    setup() {
        const register_dialogFormVisible = ref(false)
        const { proxy } = getCurrentInstance()
        const router = useRouter()

        const formData = reactive({
            account: "",
            password: ""
        });
        // 用户名校验
        const validate_account_rules = (rule, value, callback) => {
            // let regEmail = validate_name(value);
            if (value === '') {
                callback(new Error("请输入用户名"));
            } else {
                callback();
            }
        }
        // 邮箱校验
        const validate_email_rules = (rule, value, callback) => {
            let regEmail = validate_email(value);
            if (value === '') {
                callback(new Error("请输入邮箱"));
            } else if (!regEmail) {
                callback(new Error("邮箱格式不正确"));
            } else {
                callback();
            }
        }
        //校验密码
        const validate_password_rules = (rule, value, callback) => {
            let regPassword = validate_password(value);
            if (value === '') {
                callback(new Error("请输入密码"));
            } else if (!regPassword) {
                callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
            } else {
                callback();
            }
        }
        // 校验确认密码
        const validate_passwords_rules = (rule, value, callback) => {
            let regPassword = validate_password(value);
            // 获取“密码”
            const passwordValue = data.form.password;
            if (value === '') {
                callback(new Error("请再次输入密码"));
            } else if (!regPassword) {
                callback(new Error("请输入>=6并且<=20位的密码，包含数字、字母"));
            } else if (passwordValue && passwordValue !== value) {
                callback(new Error("两次密码不一致"));
            } else {
                callback();
            }
        }
        const validate_code_rules = (rule, value, callback) => {
            let regCode = validate_code(value);
            if (value === '') {
                callback(new Error("请输入验证码"));
            } else if (!regCode) {
                callback(new Error("请输入6位的验证码"));
            } else {
                callback();
            }
        }
        const data = reactive({
            form: {
                account: "",      // 用户名
                email: "",          //邮箱
                password: "",      // 密码
                passwords: "",     // 确认密码
                code: "",          // 验证码
            },
            form_rules: {
                account: [
                    { validator: validate_account_rules, trigger: 'change', required: true, }
                ],
                email: [
                    { validator: validate_email_rules, trigger: 'change', required: true, }
                ],
                password: [
                    { validator: validate_password_rules, trigger: 'change', required: true, }
                ],
                passwords: [
                    { validator: validate_passwords_rules, trigger: 'change', required: true, }
                ],
                code: [
                    { validator: validate_code_rules, trigger: 'change', required: true, }
                ]
            },
            /**
             * 获取验证码按钮交互
             */
            code_button_disabled: false,
            code_button_loading: false,
            code_button_text: "获取验证码",
            code_button_timer: null,
            // 提交按钮
            submit_button_disabled: true,
            loading: false
        })
        // 获取验证码
        const handlerGetCode = () => {

            const account = data.form.account;
            const email = data.form.email;
            const password = data.form.password;
            const passwords = data.form.passwords;
            // 校验用户名
            if (!account) {
                proxy.$message.error({
                    message: "用户名不能为空",
                    type: "error"
                })
                return false;
            }
            // 校验邮箱
            if (!validate_email(email)) {
                proxy.$message.error({
                    message: "邮箱不能为空 或 格式不正确",
                    type: "error"
                })
                return false;
            }
            // 校验密码
            if (!validate_password(password)) {
                proxy.$message.error({
                    message: "密码不能为空 或 格式不正确",
                    type: "error"
                })
                return false;
            }
            // 校验两次密码
            if (password !== passwords) {
                proxy.$message.error({
                    message: "两次密码不一致",
                    type: "error"
                })
                return false;
            }

            // 获取验证码接口
            const requestData = {
                account: data.form.account,
                email: data.form.email,
            }
            data.code_button_loading = true;
            data.code_button_text = "发送中";
            GetCode(requestData).then(response => {
                const resData = response.data;
                // 激活提交按钮
                data.submit_button_disabled = false;
                proxy.$message({
                    message: resData.message,
                    type: "success"
                })
                // 执行倒计时
                countdown();
            }).catch(error => {
                data.code_button_loading = false;
                data.code_button_text = "获取验证码";
            })
        }

        /** 倒计时 */
        const countdown = (time) => {
            if (time && typeof time !== 'number') { return false; }
            let second = time || 30;                     // 默认时间
            data.code_button_loading = false;              // 取消加载
            data.code_button_disabled = true;              // 禁用按钮
            data.code_button_text = `倒计时${second}秒`;    // 按钮文本
            // 判断是否存在定时器，存在则先清除   
            if (data.code_button_timer) { clearInterval(data.code_button_timer) };
            // 开启定时器  
            data.code_button_timer = setInterval(() => {
                second--;
                data.code_button_text = `倒计时${second}秒`;  // 按钮文本
                if (second <= 0) {
                    data.code_button_text = `重新获取`;         // 按钮文本
                    data.code_button_disabled = false;         // 启用按钮
                    clearInterval(data.code_button_timer);     // 清除倒计时
                }
            }, 1000)
        }
        /** 注册表单提交 */
        //const registerRef = ref(null);
        const submitForm = () => {
            proxy.$refs.registerRef.validate((valid) => {
                if (valid) {
                    //console.log('success submit!!')
                    register()
                } else {
                    proxy.$message.error({
                        message: "注册失败",
                        type: "error"
                    })
                    //console.log('error submit!!')
                    return false
                }
            })
        }
        // 重置注册表单
        const resetForm = () => {
            //registerRef.value = { ...data }
            //console.log(registerRef.value)
            proxy.$refs.registerRef.resetFields();// 清除定时器
            data.code_button_timer && clearInterval(data.code_button_timer);
            // 获取验证码重置文本
            data.code_button_text = "获取验证码";
            // 获取验证码激活
            data.code_button_disabled = false;
            // 禁用提交按钮
            data.submit_button_disabled = true;
            // 取消提交按钮加载
            data.submit_button_loading = false;
        }
        // 组件销毁之前 - 生命周期
        onBeforeUnmount(() => {
            clearInterval(data.code_button_timer);     // 清除倒计时
        })
        /** 注册 */
        const register = () => {
            const requestData = {
                account: data.form.account,
                email: data.form.email,
                password: data.form.password,
                verificationCode: data.form.code,
                //create: 1
            }
            data.submit_button_loading = true;
            Register(requestData).then(response => {
                const resData = response.data
                //console.log(resData.code)
                if (resData.code === 200) {
                    proxy.$message({
                        message: resData.message,
                        type: "success"
                    })
                    resetForm();
                }
                // 用户名存在
                else if (resData.code === 1024) {
                    proxy.$message.error(resData.message);
                    return false;
                }
                // 邮箱存在
                else if (resData.code === 402) {
                    proxy.$message.error(resData.message);
                    return false;
                }
                else {
                    proxy.$message({
                        message: resData.message,
                        type: "error"
                    })
                    resetForm();
                }
            }).catch(error => {
                data.submit_button_loading = false;

            })
        }
        /** 登录 */
        const doLogin = () => {
            loginPost(formData).then(res => {
                const resData = res.data.data
                if (res.data.code === 200) { //如果校验成功
                    ElMessage({
                        message: "登录成功!",
                        type: "success",
                        duration: 1000
                    });
                    console.log(resData.userid)
                    //localStorage.setItem("userid", JSON.stringify(resData.userid));
                    localStorage.setItem("userid", resData.userid);
                    localStorage.setItem("account", resData.account);
                    //var getid = localStorage.getItem("userid") //这句在projectList.vue
                    //console.log("id");
                    //console.log(getid);
                    setTimeout(() => {
                        router.push("/home/projectList");
                    }, 1000);
                } else {
                    ElMessage({
                        message: "账号或密码错误！",
                        type: "error",
                        duration: 2000
                    });
                }
            }).catch(error => {
                console.log(error);
            })
        }

        const forgetPassword = () => {
            router.push('/forgetPassword')
        }
        return {
            formData,
            data,
            disabled: computed(() => {//账号或密码输入框无输入时，登录按钮不可使用
                return formData.account.length == 0 || formData.password.length == 0;
            }),
            doLogin,
            register_dialogFormVisible,
            handlerGetCode,
            submitForm,
            resetForm,
            forgetPassword,
        }
    }
}
</script>

<style scoped>
.login-container {
    background-image: url("../../images/background1.jpg");
    background-size: 100% 100%;
    height: 100%;
    width: 100%;
    position: fixed;
}

#login_title {
    text-align: center;
    color: black;
    font-size: larger;
    margin-top: 0px;
    margin-bottom: 30px;
}

#login-panel {
    position: absolute;
    inset: 0;
    margin: auto;

    padding: 25px;
    width: 26%;
    min-width: 460px;
    height: 40%;
    min-height: 300px;
    background: rgba(255, 255, 255, 0.356);
    border-radius: 5%;
    box-shadow: 2px 2px 10px #ddd;
}

#loginButtonGroup {
    text-align: center;
}

.input {
    margin: 25px auto;
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

.form-label {
    font-size: 15px;
    width: 100px;
    text-align: left;
    font-weight: bold;
}

.register-form {
    margin-left: 40px;
    margin-right: 40px;

}

.register-dialog {
    background-image: url("../../images/background1.jpg");
    position: fixed;

}
</style>
<style>
.el-dialog {
    background-image: url("../../images/img3.jpg");
}

.el-form-item__label {
    font-weight: bold;
}
</style>